package com.fany.filesearcher;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import com.fany.utils.FileHelper;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class SQLiteFileRecorder implements IFileRecorder
{
	public SQLiteFileRecorder(Context context)
	{
		_helper = new SQLiteFileRecordAccessor(new DatabaseContext(context),
				"IFileRecorder.db", null, 1);
	}

	@Override
	public List<String> searchFile(String filter, boolean append)
	{
        return _helper.search(filter, append);
	}

	@Override
	public boolean hasLoaded()
	{
		return _helper.hasLoaded();
	}

	@Override
	public void clear()
	{
       _helper.deleteDatabase();
	}

	@Override
	public void delete(String root)
	{
		_helper.delete(root);
	}

	@Override
	public void record(List<String> paths)
	{
		_helper.insert(paths);
	}

	@Override
	public void unRecord(String path)
	{
		_helper.delete(path);
	}

	@Override
	public int getRecordCount()
	{
		return _helper.getRecordCount();
	}

	private SQLiteFileRecordAccessor _helper;

	class DatabaseContext extends ContextWrapper
	{
		public DatabaseContext(Context base)
		{
			super(base);
		}

		@Override
		public File getDatabasePath(String name)
		{
			boolean sdExist = Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState());
			if (sdExist)
			{
				String dbPath = FileHelper.getStoragePath() + File.separator + name;
				File dbFile = new File(dbPath);
				if (!dbFile.exists())
				{
					try
					{
						dbFile.createNewFile();
					}
					catch (IOException e)
					{
						e.printStackTrace();
						dbFile = null;
					}
				}
				return dbFile;
			}
			return null;
		}

		@Override
		public SQLiteDatabase openOrCreateDatabase(String name, int mode,
				SQLiteDatabase.CursorFactory factory)
		{
			try
			{
				return SQLiteDatabase.openOrCreateDatabase(
						getDatabasePath(name), null);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}

		@Override
		public SQLiteDatabase openOrCreateDatabase(String name, int mode,
				SQLiteDatabase.CursorFactory factory,
				DatabaseErrorHandler errorHandler)
		{
			try
			{
				return SQLiteDatabase.openOrCreateDatabase(
						getDatabasePath(name), null);
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return null;
		}
	}
}
